// Learn cc.Class:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html

function checkSomeData(d1,d2,dt=0){ //同一天返回true
    var t1 = new Date(d1 - dt);
    var t2 = new Date(d2 - dt);
    return t1.toLocaleDateString() == t2.toLocaleDateString();
}

var hasVideo = true;
cc.Class({
    extends: cc.Component,

    properties: {
        share : cc.Button,
        video : cc.Button,
        cbEvents: {
            "default": [],
            type: cc.Component.EventHandler,
            tooltip: "分享结果"
        }
    },
    statics:{
        hasVideo:function(){
            var lastRewardTime = cc.sys.localStorage.getItem('lastRewardTime');
            var lastHasVideo = cc.sys.localStorage.getItem('lastHasVideo');
            if(!lastRewardTime) lastRewardTime = 0
            if(!lastHasVideo || lastHasVideo.length == 0) lastHasVideo = 1
            else lastRewardTime = parseInt(lastRewardTime)
            var some = checkSomeData(lastRewardTime,Date.now(),6*60*60*1000)
            if(!some){
                hasVideo = true;
            } else {
                hasVideo = parseInt(lastHasVideo) == 2
            }
            return hasVideo;
        }
    },  
    
    onLoad(){
        hasVideo = require('RewardComponent').hasVideo()
        // hasVideo = has
    },
    start(){
        this._onShow = function(){
            let dt = Date.now() - this.n_lastShowTime
            console.log('切换时间:',dt)
            if(this.n_isShare){
                let dt = Date.now() - this.n_lastShowTime;
                if(dt > 2000){
                    this.onResp(true)
                } else {
                    global.EJMgr.showToast('分享失败，请转发到其他群试试。')
                    this.onResp(false)
                }
            }
            this.n_isShare = false;
        }.bind(this)
        CC_WECHATGAME && wx.onShow(this._onShow);
        this.video && (this.video.node.active = hasVideo);
    },
    onDestroy(){
        CC_WECHATGAME && wx.offShow(this._onShow);
    },
    onResp(res){
        cc.Component.EventHandler.emitEvents(this.cbEvents, res);
    },
    setShareData(share){
        this.shareData = share;
    },
    onClickShare(){
        cc.log('onClickShare')
        this.n_lastShowTime = Date.now();

        this.n_isShare = true;
        CC_WECHATGAME && global.Platform.share('还记得记忆中的雷电吗，快来跟我一起爽快射击吧',{parentId:global.Data._id},function(){

        })
    },
    onClickVideo(){
        var self = this;
        cc.log('onClickVideo')
        if (!CC_WECHATGAME || !wx.createRewardedVideoAd) {
            if(hasVideo){
                cc.sys.localStorage.setItem('lastRewardTime',Date.now());
                cc.sys.localStorage.setItem('lastHasVideo',2);
                hasVideo = false;
                self.video.node.active = false
                self.share.node.active = true
            }

            // if(Math.random() < 0.3){
            //     if(hasVideo){
            //         cc.sys.localStorage.setItem('lastRewardTime',Date.now());
            //         cc.sys.localStorage.setItem('lastHasVideo',2);
            //         hasVideo = false;
            //         this.video.node.active = false
            //     }
            // }
            // setTimeout(function(){
            //     self.onResp(true)
            // },1000)
            return 
        }
        if(!this.videoAd){
            this.videoAd = wx.createRewardedVideoAd({ adUnitId: 'adunit-6a07e5b943279784' });
            this.videoAd.onError((e) => {
                if(hasVideo && self.node){
                    cc.sys.localStorage.setItem('lastRewardTime',Date.now());
                    cc.sys.localStorage.setItem('lastHasVideo',2);
                    hasVideo = false;
                    self.video.node.active = false
                    self.share.node.active = true
                }
                global.EJMgr.showToast('广告加载失败')
                console.log('videoAd onError:', e);
            });
        }
        let isFirstBack = true;
        this.videoAd.load().then(() =>{
            console.log('广告准备完成')
            this.videoAd.show().then(()=>{
                console.log('广告开始显示')
                cc.game.pause();
            })}
            ).catch(err => console.log(err.errMsg)
        );
        this.videoAd.onClose((res) => {
            cc.game.resume()
            console.log('观看视频回执：', res);
            if (isFirstBack) {
                this.onResp(res.isEnded)
            }
            isFirstBack =false
        });
    }
});
